package com.lumeijin.service;

import com.lumeijin.entity.SmsCode;
import com.lumeijin.repository.SmsCodeRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

@Service
@RequiredArgsConstructor
public class SmsService {
    private final SmsCodeRepository smsCodeRepository;

    private String generateCode() {
        Random random = new Random();
        return String.format("%06d", random.nextInt(1000000));
    }

    @Transactional
    public String sendSmsCode(String phone) {
        String code = generateCode();
        SmsCode smsCode = new SmsCode(phone, code);
        smsCodeRepository.save(smsCode);
        System.out.println("模拟发送短信到手机号: " + phone + ", 验证码: " + code);
        smsCodeRepository.deleteExpiredCodes(LocalDateTime.now());
        return code; // 返回验证码用于测试
    }

    @Transactional
    public boolean verifySmsCode(String phone, String code) {
        SmsCode smsCode = smsCodeRepository.findValidCodeByPhoneAndCode(phone, code, LocalDateTime.now()).orElse(null);
        if (smsCode == null) {
            return false;
        }
        smsCodeRepository.markCodeAsUsed(phone, code);
        return true;
    }

    public boolean canSendCode(String phone) {
        List<SmsCode> recentCodes = smsCodeRepository.findByPhoneOrderByCreatedTimeDesc(phone);
        if (recentCodes.isEmpty()) {
            return true;
        }
        SmsCode latestCode = recentCodes.get(0);
        LocalDateTime oneMinuteAgo = LocalDateTime.now().minusMinutes(1);
        return latestCode.getCreatedTime().isBefore(oneMinuteAgo);
    }
}
